import {messages} from "share/common";
import React from 'react'
import {connect} from 'react-redux'
import {Form, Modal, message, Table, Popover, Spin, Select} from 'antd'
import expenseReportService from 'containers/expense-report/expense-report.service';
import errorMessage from 'share/errorMessage';
const { Option } = Select;

/**
 *  v2版英孚审批 目前不上线
 */
class YingfuSelectApproveV2 extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      yingfuInvoiceInfo: [],
      pagination: {
        total: 0
      },
      columns: [],
      yingfuApproverGroups: [],
      visible: props.visible,
      selectVisible: false,
      loading: false
    };
  }

  componentDidMount() {
    this.getList();
  }

  componentWillReceiveProps(nextProps) {
    this.setState({visible: this.props.visible})
  }

  //获取选人审批数据
  getList() {
    this.setState({loading: true})
    expenseReportService.getYingfuInvoiceInfo(this.props.expenseReport).then(res => {
      this.setState({loading: false});
      this.dataHandle(res.data);
    }).catch((e) => {
      this.setState({loading: false});
      errorMessage((e || {}).response);
    })
  }
  dataHandle = (data) => {
    let {pagination} = this.state;
    let yingfuInvoiceInfo = data;
    let columns = [{
      title: messages('expense-1.key577')/*费用*/, render: (value, record) => {
        let content = `${record.costCenterView.costCenterName},${record.costCenterView.currencyCode} ${this.filterMoney(record.costCenterView.amount, 2, true)}`;
        return (<Popover content={content}>{content}</Popover>)
      }
    }];
    yingfuInvoiceInfo.forEach(item => {
      // 190105 审批人不显示默认值
      item.costCenterView.approverGroups.forEach(approver => {
        approver.fullNameString = undefined;
        approver.userOID = undefined;
        !approver.approverUsers && (approver.approverUsers = []);
        let approverUser = approver.approverUsers && approver.approverUsers[0] || {};
        if (approver.approverUsers.length === 1) {
          approver.userOID = approverUser.userOID;
          approver.fullNameString = approverUser.fullName;
        }
      })
    });
    yingfuInvoiceInfo[0].costCenterView.approverGroups.forEach((approver, index) => {
      // 存在一个display为true则需要展示当前列
      if (approver.display ||
        yingfuInvoiceInfo.some(yfItem => yfItem.costCenterView.approverGroups[index].display)
      ) {
        let column = {
          title: approver.groupName,
          render: (value, record, rowIndex) => {
            let currentApprover = record.costCenterView.approverGroups[index];
            return (
              !currentApprover.display || currentApprover.approverUsers.length < 1 ? '' :
                <Select allowClear={true}
                        style={{width: '100%'}}
                        disabled={currentApprover.approverUsers.length < 2}
                        value={currentApprover.userOID}
                        placeholder={messages('common.select')/*请选择*/}
                        onChange={value => this.handleSelectApprover(record, index, value)}>
                  {
                    currentApprover.approverUsers.map(user => {
                      return (<Option value={user.userOID} key={user.userOID}>{user.fullName}</Option>)
                    })
                  }
                </Select>
            )
          }
        };
        columns.push(column);
      }
    });
    pagination.total = yingfuInvoiceInfo.length;
    this.setState({yingfuInvoiceInfo, pagination, columns});
  }
  handleSelectApprover = (record, index, value) => {
    let {yingfuInvoiceInfo} = this.state;
    record.costCenterView.approverGroups[index].userOID = value;
    this.setState({yingfuInvoiceInfo});
  }
  //处理表单提交
  handleSubmitApprove = () => {
    let {yingfuInvoiceInfo} = this.state;
    let usersOID = [];
    if (!yingfuInvoiceInfo || yingfuInvoiceInfo.length === 0) {
      message.error(messages('common.error1')/*获取数据失败，请稍后重试或联系管理员*/);
    }
    if (yingfuInvoiceInfo.some(approve => {
      return approve.costCenterView.approverGroups.some(lov => {
        return lov.display && lov.approverUsers.length > 0 && !lov.userOID
      })
    })) {
      message.error(messages('expense-1.key578')/*请确认审批人填写完整*/);
      return !1;
    }
    yingfuInvoiceInfo.forEach(approve => {
      approve.costCenterView.approverGroups.forEach((lov, index) => {
        if (!usersOID[index]) {
          usersOID[index] = [];
        }
        // 不显示的话需要将审批人列表全部返回
        if (!lov.display) {
          lov.approverUsers.forEach(item => {
            usersOID[index].push(item.userOID);
          });
        } else if (lov.userOID) {
          usersOID[index].push(lov.userOID);
        }
      })
    });
    usersOID = JSON.stringify(usersOID.filter(approver => approver.length > 0));

    //提交
    this.props.onOk(usersOID);
  };
  //处理表单关闭
  handleCancelApprove = () => {
    this.props.afterClose();
  };

  render() {
    const {visible, yingfuInvoiceInfo, loading, columns} = this.state;
    let modalTitle = <div><span>{messages('expense-1.key579')/*选择成本中心审批人*/}</span><br/><span
      style={{color: 'red', fontSize: 14}}>({messages('expense-1.key580')/*请选择成本中心对应的审批人并仔细核对，否则报销单将被驳回*/})</span></div>;
    return (
      <div>
        <Modal title={modalTitle} okText={messages('common.submit')/*提交*/} visible={visible} onOk={this.handleSubmitApprove} width={800}
               onCancel={this.handleCancelApprove}>
          <Spin spinning={loading}>
            <Table size="small"
                   dataSource={yingfuInvoiceInfo}
                   pagination={false}
                   bordered
                   columns={columns}>
            </Table>
          </Spin>
        </Modal>
      </div>
    );

  }
}

YingfuSelectApproveV2.propTypes = {
  visible: React.PropTypes.bool, //导入弹框是否可见
  expenseReport: React.PropTypes.object, //报销单对象信息
  onOk: React.PropTypes.func,       //英孚审批提交
  afterClose: React.PropTypes.func //关闭后的回调
}

function mapStateToProps(state) {
  return {}
}

const WrappedYingfuSelectApprove = Form.create()(YingfuSelectApproveV2)

export default connect(mapStateToProps)(WrappedYingfuSelectApprove)

